﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Excel2DbTool.Models
{
    public class DbRowMapping
    {
        private IList<IDbFieldVal> dbFieldMappings;

        public DbRowMapping()
        {
            dbFieldMappings = new List<IDbFieldVal>(50);
        }

        public DbRowMapping(IList<IDbFieldVal> dbFieldMappings)
        {
            if (dbFieldMappings == null)
            {
                throw new ArgumentNullException();
            }

            this.dbFieldMappings = dbFieldMappings;
        }

        public IDbFieldVal this[int i]
        {
            get
            {
                return dbFieldMappings[i];
            }
        }

        public string GetValStr()
        {
            List<string> strs = new List<string>(500);
            foreach (var item in dbFieldMappings)
            {
                strs.Add(string.Format("{0}", item.Val.ToString()));
            }

            return string.Join(",", strs);
        }
    }


    public class DbRowMappingNew
    {
        private IList<DbFieldMapping> dbFieldMappings;

        public DbRowMappingNew()
        {
            dbFieldMappings = new List<DbFieldMapping>(50);
        }

        public void AddFieldMapping(DbFieldMapping dbfm)
        {
            dbFieldMappings.Add(dbfm);
        }

        public object GetValByOrginFieldName(string orginFieldName)
        {
            return dbFieldMappings.FirstOrDefault(dbfm => string.Equals(dbfm.OrignFieldName, orginFieldName)).Val;
        }

        public object GetValByTargetFieldName(string targetFieldName)
        {
            return dbFieldMappings.FirstOrDefault(dbfm => string.Equals(dbfm.TargetFieldName, targetFieldName)).Val;
        }

        public DbFieldMapping this[int i]
        {
            get
            {
                return dbFieldMappings[i];
            }
        }

        public string GetValStr()
        {
            List<string> strs = new List<string>(500);
            foreach (var item in dbFieldMappings)
            {
                if (item is OracleTableStrFieldReferToOtherFieldInSameTable)
                {
                    var field = ((OracleTableStrFieldReferToOtherFieldInSameTable)item);
                    DbFieldMapping dfm = getFieldReferTo(field);
                    item.Val = field.Deal(dfm.Val.ToString());
                }

                strs.Add(string.Format("{0}", item.Val.ToString()));
            }

            return string.Join(",", strs);
        }

        DbFieldMapping getFieldReferTo(OracleTableStrFieldReferToOtherFieldInSameTable refer)
        {
            return dbFieldMappings.FirstOrDefault(item => item.TargetFieldName == refer.FieldNameReferTo);
        }

        public override string ToString()
        {
            return GetValStr();
        }
    }
}
